package com.freecloud.plug.lettuce;

import io.lettuce.core.LettuceFutures;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: maomao
 * @Date: 2020-03-31 09:51
 */
public class PipelineTest {
    public static void main(String[] args) {
        RedisClient client = RedisClient.create("redis://192.168.10.110:30001");
        // 线程安全的长连接，连接丢失时会自动重连
        StatefulRedisConnection<String, String> connection = client.connect();
        // 取消自动flush
        connection.setAutoFlushCommands(false);
        List<RedisFuture<?>> redisFutures = new ArrayList<>();

        RedisAsyncCommands asyncCommands = connection.async();

        int count = 5000;
        for (int i = 0; i < count; i++) {
            String key = "free:test:key-" + (i + 1);
            String value = "value-" + (i + 1);
            redisFutures.add(asyncCommands.set(key, value));
            redisFutures.add(asyncCommands.expire(key, 20000));
        }
        long start = System.currentTimeMillis();
        connection.flushCommands();
        boolean result = LettuceFutures.awaitAll(10, TimeUnit.SECONDS, redisFutures.toArray(new RedisFuture[0]));
        System.out.println("result : " + result);
        System.out.println("Lettuce cost Times : " + (System.currentTimeMillis() - start));
    }
}
